<template>
  <el-row>
    <el-col :span="12">
      <el-image src="/src/assets/banner/banner2.jpg"/>
    </el-col>
    <el-col :span="12">
      <el-form label-width="auto" style="max-width: 300px" class="regForm">
        <h1>用户注册</h1>
        <el-form-item>
          <el-input v-model="regInfo.username" placeholder="注册：请输入您独一无二的用户名" clearable suffix-icon="User"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="regInfo.password" placeholder="注册：请输入让别人无法洞察的密码" clearable suffix-icon="Hide"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="regInfo.captchaInput" placeholder="请输入验证的验证码" clearable
                    style="width: 170px;margin-right: 10px" suffix-icon="Checked"/>
          <el-image :src="captchaImageBase64Data" @click="getCaptcha"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="regBtn1" @click="reg()">注册</el-button>
          <el-button type="danger" class="regBtn2" @click="regInfoAgain">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import userApi from '@/api/userApi.js';
import {ref} from "vue";
import {ElLoading, ElMessage, ElNotification} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();
//保存验证码
const captchaImageBase64Data = ref("");
//用户注册信息
const regInfo = ref({
  username: '',
  password: '',
  key: '',
  captchaInput: '',
});

//注册
function reg() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.6)',
  })
  userApi.reg(regInfo.value)
      .then(resp => {
        loading.close()
        if (resp.code === 10000) {
          ElMessage.success(resp.msg);
          router.push('/user/login');
          ElNotification({
            title: 'Success',
            message: '请重新登录~~~',
            type: 'success',
          });
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

function regInfoAgain() {
  regInfo.value = {
    username: '',
    password: '',
    key: '',
    captchaInput: '',
  }
}

//获取验证码
function getCaptcha() {
  userApi.captcha()
      .then(resp => {
        regInfo.value.key = resp.data.key
        //console.log(resp.data.captchaImageBase64Data)
        captchaImageBase64Data.value = resp.data.captchaImageBase64Data
      })
}

getCaptcha()
</script>

<style scoped>
.regForm {
  margin: 100px;
}

.regForm h1 {
  text-align: center;
  margin-bottom: 20px;
}

.regBtn1, .regBtn2 {
  width: 45%;
}
</style>